package com.xlf.service.blog.test;


import com.xlf.common.core.constant.ArticleConstants;
import com.xlf.common.core.util.StringUtils;
import com.xlf.common.core.util.spring.SpringUtils;
import com.xlf.common.redis.service.RedisCache;
import com.xlf.service.blog.domain.Article;
import com.xlf.service.blog.service.ArticleService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.Map;

/**
 * 同步文章的访问量pv到数据库
 */
@Slf4j
@Service
public class UpdateArticleViewTask implements Runnable{

    @Resource
    ArticleService articleService;

    @Autowired
    RedisCache redisCache;

    @Transactional
    @Override
    public void run() {
        //id,
        Map<String, Integer> cacheMap = redisCache.getCacheMap(ArticleConstants.ARTICLE_VIEW);
        log.info("浏览量开始同步数据库");
        if(StringUtils.isNotEmpty(cacheMap))
        {
            cacheMap.forEach((k,v)->{
                try {
                    articleService.lambdaUpdate().set(Article::getArticleReadNum, v).eq(Article::getId, k).update();
                    redisCache.removeMapKey(ArticleConstants.ARTICLE_VIEW,k);
                    log.info("同步文章："+k+"浏览量成功");
                    //ARTICLE_VIEW
                } catch (Exception e) {
                    log.warn("同步文章："+k+"浏览量失败");
                }
            });
        }
    }
}
